<?php
declare (strict_types = 1);

namespace app\command;

use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use think\facade\Config;
use think\facade\Cache;
use app\model\DingGroup as DingGroupModel;
use app\model\DingUser as DingUserModel;

class Roster extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('roster')
            ->setDescription('the roster command');        
    }

    private function getAccessToken()
    {

        $redis = Cache::store('redis');
        $access_token = $redis->get('access_token');
        if(empty($access_token)){
            $url = sprintf("https://oapi.dingtalk.com/gettoken?appkey=%s&appsecret=%s",Config::get('dingding.appKey'),Config::get('dingding.appSecret'));
            $res = json_decode(curl_get($url),true);
            $access_token = $res['access_token'];
            $redis->set('access_token',$access_token,7000);
        }
        return $access_token;
    }


    private function createOrUpdatePart($access_token){
        $dingGroupModel = new DingGroupModel;

        $url = sprintf("https://oapi.dingtalk.com/department/list?access_token=%s",$access_token);
        $res = curl_get($url);

        $part_list = json_decode($res,true)['department'];

        foreach ($part_list as $key => $part) {
            $isExist = DingGroupModel::find($part['id']);
            $parent_id = $part['id'] == 1 ? 0 : $part['parentid'];
            if($isExist){
                $dingGroupModel->update(['name' => $part['name'],'parent_id' => $parent_id],['id' => $part['id']]);
            }else{
                $dingGroupModel->insert(['id' => $part['id'],'name' => $part['name'],'parent_id' => $parent_id]);                                  
            }

        }
    }


    private function createOrUpdatePerson($access_token){

        $isNext = true;
        $offset = 0;
        $size = 20;
        $dingUserModel = new DingUserModel;

        while($isNext){
            $url = sprintf("https://oapi.dingtalk.com/topapi/smartwork/hrm/employee/queryonjob?access_token=%s",$access_token);

            echo $offset."---".$size."<br/>";

            $res = curl_post($url,[
                'status_list' => '2,3,5,-1',
                'offset' => $offset,
                'size' => $size
            ]);

            $result = json_decode($res,true)['result'];

            if(!isset($result['next_cursor'])){
                $isNext = false;
            }

            $user_list = $result['data_list'];

            foreach ($user_list as $key => $userid) {

                $url = sprintf("https://oapi.dingtalk.com/user/get?access_token=%s&userid=%s",$access_token,$userid);
                $res = curl_get($url);
                $userInfo = json_decode($res,true);

                if(!isset($userInfo['userid'])){
                    continue;
                }

                $user = DingUserModel::find($userid);
                if(empty($user)){
                    $dingUserModel->insert([
                        'id' => $userid,
                        'name' => $userInfo['name'],
                        'unionid' => $userInfo['unionid'],
                        'mobile' => $userInfo['mobile'],
                        'hiredDate' => isset($userInfo['hiredDate']) ? $userInfo['hiredDate']/1000 : 0,
                        'department' => implode($userInfo['department'], ','),
                        'avatar' => !empty($userInfo['avatar']) ? $userInfo['avatar'] : 'https://unote.uupt.com/uunote/img/logo.50f67225.png',
                        'jobnumber' => isset($userInfo['jobnumber']) ? $userInfo['jobnumber'] : '',
                        'position' => isset($userInfo['position']) ? $userInfo['position'] : ''
                    ]);
                }else{
                    $dingUserModel->update([
                        'name' => $userInfo['name'],
                        'unionid' => $userInfo['unionid'],
                        'mobile' => $userInfo['mobile'],
                        'hiredDate' => isset($userInfo['hiredDate']) ? $userInfo['hiredDate']/1000 : 0,
                        'department' => implode($userInfo['department'], ','),
                        'avatar' => !empty($userInfo['avatar']) ? $userInfo['avatar'] : 'https://unote.uupt.com/uunote/img/logo.50f67225.png',
                        'jobnumber' => isset($userInfo['jobnumber']) ? $userInfo['jobnumber'] : '',
                        'position' => isset($userInfo['position']) ? $userInfo['position'] : ''
                    ],['id' => $userInfo['userid']]);                        
                }

            }
            $offset += $size;
            sleep(10);
        }
    }



    protected function execute(Input $input, Output $output)
    {

        $access_token = $this->getAccessToken();
        $this->createOrUpdatePart($access_token);
        $this->createOrUpdatePerson($access_token);

        // 指令输出
        $output->writeln('roster');
    }
}
